//测试商品编号272892
define(function(require){
	var $=require("jq");
	var PZ_Dialog=require("pz_use_dialog.js");
	//给详情页导航加个底线
	$(".nav-bar-main").css("border-bottom","1px solid #ef363e");
	
	//优惠信息
	function GoodThing(obj){
		this.foldObj=obj;
		var _this_=this;
		this.foldObj.find("a").click(function(){
			var this$=$(this);
			if(this$.data("isEx")){
				_this_.foldObj.find(".msg:gt(1)").hide();
				this$.data("isEx",false);
				this$.html("详细>>");
			}else{
				_this_.foldObj.find(".msg:gt(1)").show();
				this$.data("isEx",true);
				this$.html("<<折叠");
			}
		});
	}
	var foldButton=$(("#goodFold"));
	if(foldButton.length>0){
		var msgFold=new GoodThing(foldButton.parent());
	}

	// 判断array1属否和arry2中的元素一样	
	function eqArray(array1,array2){
		if(haveArray(array1,array2)&&haveArray(array2,array1)){
			return true;
		}
	}
	
	// 判断array1中是否包含arry2中的所有元素
	function haveArray(array1,array2){
		for(var i=-1;array2[++i];){
			if(!haveItem(array1,array2[i])){
				return false;
			}
		}
		return true;
	}
	
	// 判断数组是否包含元素
	function haveItem(array,item){
		for(var i=-1;array[++i];){
			if(array[i]==item){
				return true;
			}
		}
		return false;
		
	}
//choose3-------------------------start
	var staticVarObj={
		selectAttrGroupClass:"item-bg",
		selectAttrClass:"selected",
		canAttrClass:"can",
		noThingClass:"noThing",
		unCanAttrClass:"",
		chooseMap:{}
	}
	
	var toolFun={
		haveItem:haveItem,
		haveArray:haveArray,
		eqArray:eqArray,
		adaptMap:function(map,array2){
			for(var name in map){
				var array1=map[name];
				if(this.haveArray(array1,array2)){
					return true;
				}
			}
			return false;
		},
		eqMap:function(map,array2){
			for(var name in map){
				var array1=map[name];
				if(this.eqArray(array1,array2)){
					return true;
				}
			}
			return false;
		}
	}
	
	function Attr(obj$){
		this.context$=obj$;
		this.init();
	}
	Attr.prototype={
		init:function(){
			
		},
		addSelect:function(){
			this.context$.addClass(staticVarObj.selectAttrClass);
		},
		removeSelect:function(){
			this.context$.removeClass(staticVarObj.selectAttrClass);
		},
		addCan:function(){
			this.context$.addClass(staticVarObj.canAttrClass);
		},
		addNoThing:function(){
			this.context$.addClass(staticVarObj.noThingClass);
		},
		removeCan:function(){
			this.context$.removeClass(staticVarObj.canAttrClass);
		},
		getAttrValue:function(){
			return this.context$.attr("data-value");
		},
		hasCan:function(){
			if(this.context$.hasClass(staticVarObj.canAttrClass)){
				return true;
			}else{
				return false;
			}
		},
		hasSelect:function(){
			
		},
		getShowText:function(){
			var context$=this.context$;
			return context$.find("a").attr("title");
		}
	}
	
	function AttrGroup(obj$){
		this.context$=obj$;
		this.init();
	}
	AttrGroup.prototype={
		init:function(){
			var _this=this;
			this.attrs=[];
			this.context$.find(".dd div").each(function(){
				var this$=$(this);
				var attr=new Attr(this$);
				_this.attrs[_this.attrs.length]=attr;
				if(this$.hasClass(staticVarObj.selectAttrClass)){
					_this.selectAttr=attr;
				};
			});
		},
		getSelectAttr:function(){
			return this.selectAttr;
		},
		getSelectAttrValue:function(){
			var attr=this.getSelectAttr();
			return attr!=null?attr.getAttrValue():null;	
		},
		emptySelect:function(){
			if(this.selectAttr){
				var attr=this.selectAttr;
				this.selectAttr=null;
				attr.removeSelect();
				return attr;
			}else{
				return false;
			}
		},
		getAttrs:function(){
			return this.attrs;
		},
		select:function (attr){
			if(this.selectAttr){
				this.selectAttr.removeSelect();
			}
			this.selectAttr=attr;
			attr.addSelect();
		},
		removeSelectClass:function(){
			this.context$.removeClass(staticVarObj.selectAttrGroupClass);
		},
		addSelectClass:function(){
			this.context$.addClass(staticVarObj.selectAttrGroupClass);
			
		},
		addAllAttrsCan:function(){
			var attrs=this.attrs;
			for(var i=0;i<attrs.length;i++){
				attrs[i].addCan();
			}
		},
		removeAllAttrsCan:function(){
			this.emptySelect();
			var attrs=this.attrs;
			for(var i=0;i<attrs.length;i++){
				attrs[i].removeCan();
			}
		}
	}
	
	//选择属性版本3
	function Choose3(obj$){
		/**
		 * 将所给字符串索引地图，名值反置
		 * 并将字符串，拆分为数组
		 */
		var mapStr=obj$.attr("data-choose-value");
		var map=$.parseJSON(mapStr);
		var map2={};
		for(var indexStr in map){
			var array=indexStr.split(",");
			map2[map[indexStr]]=array;
		}
		staticVarObj.chooseMap=map2||staticVarObj.chooseMap;
		this.context$=obj$;
		this.init();
		this.initClass();
		this.blind();
		this.showSelectOption();
	}
	Choose3.prototype={
		init:function(){
			this.attrGroups=[];
			var _this=this;
			this.context$.find("li.attrGroup").each(function(){
				_this.attrGroups[_this.attrGroups.length]=new AttrGroup($(this));
			});
			
		},
		initClass:function(){
			var attrGroups=this.attrGroups;
			var selectArray=[];
			for(var i=0;i<attrGroups.length;i++){
				var attrGroup=attrGroups[i];
				var attrs=attrGroup.getAttrs();
				for(var j=0;j<attrs.length;j++){
					var attr=attrs[j];
					selectArray[i]=attr.getAttrValue();
					if(toolFun.adaptMap(staticVarObj.chooseMap,selectArray)){
						attr.addCan();
						var tempArray=this.getSelectValues();
						tempArray[i]=attr.getAttrValue();
						if(!toolFun.eqMap(staticVarObj.chooseMap,tempArray)){
							attr.addNoThing();
						}
					}else{
						attr.removeCan();
					};
				}
				selectArray[i]=attrGroup.getSelectAttrValue();
			}
		},
		blind:function(){
			var _this=this;
			var attrGroups=this.attrGroups;
			for(var i=0;i<attrGroups.length;i++){
				var attrGroup=attrGroups[i];
				var attrs=attrGroup.getAttrs();
				for(var j=0;j<attrs.length;j++){
					var attr=attrs[j];
					attr.context$.click(
						_this.createBlindFun(i,attr,attrGroup,_this)
					);
				}
			}
		},
		haveFirst:false,
		createBlindFun:function(index,attr,attrGroup,_choose){
			var _this=_choose;
			return function(){
				if(attr.hasCan()){
					if(!_this.haveFirst){
						_this.removeAllNoThing();
						_this.haveFirst=true;
					}
					_this.removeSelect(index);
					attrGroup.select(attr);
					var attrGroups=_this.attrGroups;
					for(var i=index+1;i<attrGroups.length;i++){
						var attrGroup2=attrGroups[i];
						var attrs=attrGroup2.getAttrs();
						var selectArray=_this.getSelectValues(i);
						for(var j=0;j<attrs.length;j++){
							var attr2=attrs[j];
							selectArray[i]=attr2.getAttrValue();
							if(toolFun.adaptMap(staticVarObj.chooseMap,selectArray)){
								attr2.addCan();
							}else{
								attr2.removeCan();
							}
						}
						if(attrGroup2.getSelectAttr()==null||!attrGroup2.getSelectAttr().hasCan()){
							attrGroup2.emptySelect();
							attrGroup2.addSelectClass();
							_this.removeAttrsSelect(i+1);
							_this.changeAddButtonClass();
							_this.showSelectOption();
							return ;
						}
					}
					_this.tiaoZhuan(_this.getSelectValues());
				}else{
					return ;
				}
			}
		},
		removeAttrsSelect:function(start){
			var attrGroups=this.attrGroups;
			for(var i=start;i<attrGroups.length;i++){
				var attrGroup=attrGroups[i];
				attrGroup.removeAllAttrsCan();
			}
		},
		removeSelect:function(start){
			var attrGroups=this.attrGroups;
			for(var i=start;i<attrGroups.length;i++){
				attrGroups[i].removeSelectClass();
			}
		},
		removeAllNoThing:function(){
			$(".item").removeClass(staticVarObj.noThingClass);
		},
		getSelectValues:function(end){
			var attrGroups=this.attrGroups;
			if(end||end==0){
				end=end+1;
			}
			end=end||attrGroups.length;
			end=end<attrGroups.length?end:attrGroups.length;
			var selectArray=[];
			for(var i=0;i<end;i++){
				var selectValue=attrGroups[i].getSelectAttrValue();
				if(selectValue){//考虑没有选中值时的情况
					selectArray[selectArray.length]=selectValue;
				}
			}
			return selectArray;
		},
		getSelectAttrs:function(){
			var attrs=[];
			var attrGroups=this.attrGroups;
			for(var i=0;i<attrGroups.length;i++){
				var selectAttr=attrGroups[i].getSelectAttr();
				if(selectAttr){
					attrs[attrs.length]=selectAttr;
				}
			}
			return attrs;
		},
		tiaoZhuan:function(selectValues){
			selectValues=selectValues||[];
			var chooseMap=staticVarObj.chooseMap;
			for(var id in chooseMap){
				if(toolFun.eqArray(chooseMap[id],selectValues)){
					window.location="/product/"+id+".html"
					return true;
				}
			}
			return false;
		},
		isAddToCart:function(){
			var selectLength=this.getSelectValues().length;
			var groupSize=this.attrGroups.length;
			if(selectLength==groupSize){
				return true;
			}else{
				false;
			}
			
		},
		changeAddButtonClass:function(){
			var addButton=$("#addToCart");
			var length1=this.getSelectValues().length;
			var length2=this.attrGroups.length;
			if(length1<length2){
				addButton.removeClass("add-cart");
				addButton.addClass("add-cart-not");
			}else{
				addButton.removeClass("add-cart-not");
				addButton.addClass("add-cart");
			}
		},
		showSelectOption:function(){
			var attrs=this.getSelectAttrs();
			var text="<span>您已选择：</span>";
			for(var i=0;i<attrs.length;i++){
				text=text+"<strong>"+attrs[i].getShowText()+"&nbsp;&nbsp;</strong>";
			}
			$("#select-show").html(text);
		}
	}
	var choose3=new Choose3($("#J_Choose"));
	
	//赠品选择
	function SelectGift(content){
		var _this = this;
		this.content = content;
		this.gou = $(".gou",this.content);
		this.foldButton = $(".fold",this.content);
		this.foldButton.click(function(e){
			_this.fold(e);
		});
		this.giftList = $(".gifts-list",this.content);
		$(".li-img",this.giftList).click(function(){
			_this.select($(this));
		});
		this.selectGift = $(".gifts-select",this.content).click(function(e){
			_this.fold(e);
		});
		this.jieduan();
	}
	
	SelectGift.prototype = {
		defaultGiftId : 0,
		isExpand : false,
		jieduan : function(){
			$(".gift-title",this.content).each(function(){
				var limitLength = 35;
				var html = $(this).html();
				if(limitLength<html.length){
					html = html.substring(0,limitLength)+"...";
				};
				$(this).html(html);
			}).show();
			
		},
		fold : function(event){
			if(event){
				event.stopPropagation();
			}
			var isExpand = this.isExpand = !this.isExpand;
			if(isExpand){
				this.giftList.show();
				this.foldButton.removeClass("close").addClass("open");
			}else{
				this.giftList.hide();
				this.foldButton.removeClass("open").addClass("close");
			}
		},
		select : function(selectDom){
			selectDom.addClass("on").siblings().removeClass("on");
			selectDom.append(this.gou);
			this.setValue(selectDom);
			this.fold();
		},
		setValue : function(selectDom){
			var imgSrc = selectDom.find(".gift-img").attr("src");
			var title = selectDom.find(".gift-title").html();
			var numStr = selectDom.find(".gift-num").html();
			var giftId = selectDom.attr("data-id");
			var productLink = selectDom.find("a.productLink").attr("href");
			this.selectGift.find(".gift-img").attr("src",imgSrc);
			this.selectGift.find(".gift-title").html(title);
			this.selectGift.find(".gift-num").html(numStr);
			this.selectGift.attr("data-id",giftId);
			this.selectGift.find("a.productLink").attr("href",productLink);
		},
		getSelectId : function(){
			if(this.selectGift.length==0){
				return this.defaultGiftId;
			}
			return this.selectGift.attr("data-id");
		}
	};
	
	var selectGift = new SelectGift($("#product-gifts-select"));
	
	/*
	 * 实现购物车的添加商品
	 */
	function addCart(){

		var input$=$("#buy-num");

		function canBuyNum(changNum){
			var value=input$.val();
			if(/\d+/.test(value)&&value>0&&input$.attr("data-buy-num")-value>=0){
				return true;
			}else{
				input$.val(changNum);
				return false;
			}
		}
		
		
		$("#addNumButton").on("click",function(){
			var _this=$(this);
			var input=$("#buy-num");
			if(validation(input.val())&&input.val()>0){
				input.val(parseInt(input.val())+1);
			}else{
				input.val(1);
			}
			
			canBuyNum(input$.attr("data-buy-num"));
		});
		
		$("#reduceNumButton").on("click",function(){
			if(input$.attr("data-buy-num")==0){
				return ;
			}
			var _this=$(this);
			var input=$("#buy-num");
			if(validation(input.val())&&input.val()>1){
				input.val(input.val()-1);
			}else{
				input.val(1);
			}
			canBuyNum(1);
		});
		
		$("#buy-num").on("keyup",function(){
			if(/\d+/.test(input$.val())&&input$.val()>input$.attr("data-buy-num")){
				canBuyNum(input$.attr("data-buy-num"));
			}else{
				canBuyNum(1);
			}
			
		});
		
		$("#addToCart").on("click",function(e){
			var _this=$(this);
			if(input$.attr("data-buy-num")==0){
				return;
			}
			if(_this.hasClass("add-cart-not")){
				return;
			}
			var _this=this;
			var url="/addItem.do";
			var input=$("#buy-num");
			
			
			if(validation(input.val())&&input.val()>0){
				var this2 = $(this);
				
				function addProduct(autoDel){
					$.get(url+"?rand="+Math.random(),{selected : selectGift.getSelectId(),productId:this2.attr("data-id"),amount:$("#buy-num").val(),agentId:this2.attr("data-agentid"),autoDel:autoDel},function(json){

						if(json.state=="success"){
							if(json['message'] != null && json['message'].length > 0){
								var tips=new PZ_Dialog({
									  type:"alert",
									  height:107,
									  tipsText:json['message'],
									  buttonCancelText:"知道了", 
									  mask:0.3,
									  isDrag:true                // 开起拖动
								});
							}
							successResult(json,_this);
						}else if(json.state=="error_login"){
							var tips=new PZ_Dialog({
								  type:"confirm",
								  height:107,
								  tipsText:"只有登录才能购买商品",
								  buttonSureText:"去登录", 
								  buttonCancelText:"知道了", 
								  mask:0.3,
								  callBack:function(){         //回调函数
										window.location="/login.do?toUrl="+window.location;
								  },
								  isDrag:true                // 开起拖动
							});
						}else if(json.state=="error_cannotbuy"){
							var tips=new PZ_Dialog({
								  type:"alert",
								  height:107,
								  tipsText:json['msg'],
								  buttonCancelText:"知道了", 
								  mask:0.3,
								  isDrag:true                // 开起拖动
							});
						}else if(json.state=="ask_autoDel"){
							var tips=new PZ_Dialog({
								  type:"confirm",
								  height:107,
								  width:320,
								  tipsText:json['msg'],
								  buttonSureText:"移除", 
								  buttonCancelText:"取消", 
								  mask:0.3,
								  callBack:function(){         //回调函数
									  addProduct(1);
								  },
								  isDrag:true                // 开起拖动
							});
						}else{
							failure(json);
						}
						
						
					},"json");
				}
				addProduct(0);//去掉通告
//				//通告添加
//				var lazySong = new PZ_Dialog({
//							  type:"confirm",
//							  height:130,
//							  text:"温馨提示",
//							  tipsText:"“品质365商城即日起逐步恢复发货，由于春节期间货品累积，到货时间可能延迟，敬请理解！”",
//							  buttonSureText:"继续购买", 
//							  buttonCancelText:"取消", 
//							  callBack:addProduct,
//							  mask:0.3
//						  });
	
				
			}else{
				
			};
			//shopCart.attr("isopen","no");
		});
		// 获取购物车和当前产品图片
		var productImg=$(".J_ImagesHook");
		function successResult(json,thisObj){
			var shopCartNum=$("#js-shopcart").find(".cart-num");

			var cartPosLeft = $(window).width(),
				cartPosTop  = $(window).height()/2+$(document).scrollTop()+40;
			
			var offset=$(thisObj).offset();
			var div=$("<div id='push-shop-cart' style='left:"+offset.left+"px;top:"+(offset.top+1)+"px;'><img src='"+productImg.attr("src")+"' width='31' height='31'></div>");
			$("body").append(div);
			
			div.fadeIn("fast",function(){
			
				$(this).animate({left:cartPosLeft-50,top:cartPosTop,opacity:0},"slow",function(){
					div.remove();
					

				});

			});
			
			//修改最大可买数
			var maxBuyNum=json.canBuyNum;
			input$.attr("data-buy-num",maxBuyNum);
			if(maxBuyNum==0){
				window.location=window.location;
			
			}
			if(maxBuyNum-input$.val()<0){
				input$.val(maxBuyNum);
			}
		}
		
		function failure(json){
				var tips=new PZ_Dialog({
					  type:"alert",
					  height:107,
					  tipsText:json.msg,
					  mask:0.3,
					  cancelCallBack:function(){
						alert("取消按钮"); 
					  },
					  isDrag:true                // 开起拖动
				});
				
				if(json.msg='此款商品只能vip用户购买'){
					return ;
				}
				input$.val(input$.attr("data-buy-num"));
		}
		
		function validation(str){
			if(/\d+/.test(str)){
				return true;
			}else{
				return false;
			}
		}
	}
	
	addCart();
	
	
	/**
	 * 选项卡
	 */
	function SelectOptionManager(obj){
		var _this_=this;
		// init(obj);
		this.switchObj=obj;
		this.tabs=$("ul.tab li",obj);
		this.tabCons=$("div.pra",obj);
		this.tabs.click(function(){
			if(!$(this).hasClass("on")){
				$(this).addClass("on").siblings().removeClass("on");
				_this_.tabCons.eq($(this).index()).addClass("pra-show").siblings().removeClass("pra-show");	
			};
		});

	};
	SelectOptionManager.prototype={
		selectOneOption:function(num){
			return this.tabs.eq(num).click();
			
			//this.switchObj.find(".tab li:eq("+num+")").click();
		}
	}
	var tab=new SelectOptionManager($("#J_TabSwitch"));
	
	$("#gotoPinglun").click(function(){
		var pos=tab.selectOneOption(3);
		$("html,body").animate({scrollTop:pos.offset().top});
	});
});

